package com.vf.cloud.paas.app.agent.common.server.signalling.streamer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import com.vf.cloud.paas.app.agent.common.server.signalling.channel.StreamerChannelInitializer;
import com.vf.cloud.paas.app.agent.common.server.signalling.pool.StreamerPool;
import com.vf.cloud.paas.common.cirrus.Cirrus;
import com.vf.cloud.paas.common.service.IRedis;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class StreamerServer {
	
	@Autowired
	private IRedis redisImpl;

	private EventLoopGroup boss;
	private EventLoopGroup work;
	private Channel channel;

	@Async
	public void run() {
		try {
			if(Cirrus.streamerIsConnected) {
				destroy();
			}
			
			if(Cirrus.Streamer_Port==0) {
				log.info(">>> StreamerServer:配置有误，请检查端口.");
				return;
			}
			
			ServerBootstrap bootstrap = new ServerBootstrap();
			boss = new NioEventLoopGroup();
			work = new NioEventLoopGroup();

			log.info(String.format(">>> StreamerServer:开始启动[%s]." ,Cirrus.Streamer_Port));
			bootstrap.group(boss, work);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(512 * 1024, 1024 * 1024));
			bootstrap.childHandler(
					new StreamerChannelInitializer(redisImpl));
			channel = bootstrap.bind(Cirrus.Streamer_Port).sync().channel();
			log.info(String.format(">>> StreamerServer listening on *:%s." ,Cirrus.Streamer_Port));
			
			Cirrus.streamerIsConnected=true;
			
			if(channel!=null  && channel.closeFuture()!=null) {
				channel.closeFuture().sync();
			}
		} catch (Exception e) {
		} finally {
			if(channel!=null) channel.close();
			if(work!=null) work.shutdownGracefully();
			if(boss!=null) boss.shutdownGracefully();
			log.info(String.format(">>> StreamerServer:已停止[%s].", Cirrus.Streamer_Port));
		}
	}

	public void destroy() {
		StreamerPool.closeAll();
		if(channel!=null) {
			channel.close();
		}
		if(work!=null) {
			work.shutdownGracefully();
		}
		if(boss!=null) {
			boss.shutdownGracefully();
		}
		Cirrus.streamerIsConnected=false;
	}

}
